package org.ma5d;

import java.util.concurrent.TimeUnit;

import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;

public class SetterTest {
    public static void main(String[] args) {
        // 1.定义jobDetail
        JobDetail job = JobBuilder.newJob(SetterJob.class)
                .withIdentity("job1", "jGroup1")
                .usingJobData("name", "Doubibiji") // 通过key-value形式设置参数
                .usingJobData("description", "job的参数") // 通过key-value形式设置参数
                .build();

        // 2.定义触发器
        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("trigger1", "tGroup1")
                .usingJobData("year", 2024) // 通过key-value形式设置参数
                .usingJobData("description", "trigger的参数") // 通过key-value形式设置参数
                // 立刻执行
                .startNow()
                // 触发策略，用简单的触发策略，就是按照时间间隔执行
                .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                        // 5秒执行一次
                        .withIntervalInSeconds(1)
                        // 一直重复
                        .withRepeatCount(0))
                .build();

        try {
            // 3.定义调度器
            Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
            // 设置任务和触发器，由触发器进行分派任务
            scheduler.scheduleJob(job, trigger);
            scheduler.start();

            // 让主线程延迟执行，scheduler如果shutdown，则所有的定时任务会取消。
            TimeUnit.SECONDS.sleep(20);
            scheduler.shutdown();
        } catch (SchedulerException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public class SetterJob implements Job {

        // 需要与传递的key名称相同
        private String name;
        private int year;
        private String description;

        // 定义set方法
        public void setName(String name) {
            this.name = name;
        }

        public void setYear(int year) {
            this.year = year;
        }

        public void setDescription(String description) {
            this.description = description;
        }

        @Override
        public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
            System.out.println("--------");

            // 获取到传递的数据
            System.out.println("name:" + name);
            System.out.println("year:" + year);
            System.out.println("description:" + description);
        }
    }
}
